import { Subscription } from 'rxjs';
import { ReactiveCommand } from './cc3/ReactiveCommand';

/*
    import { nc } from './libs/rxjs/NotificationCenter';

    // 订阅
    nc.subscribe('test', data => this.log('got', data)),

    // 发送
    nc.post('test', { a: 12 });

*/

class NotificationCenter {

    constructor() {
        this.subscribeCustomEventTarget();
    }

    rc: ReactiveCommand<{ key: string, data: any }> = ReactiveCommand.Create();

    post(key: string, data: any) {
        this.rc.execute({ key, data });
    }

    subscribe<T>(key: string, next: (data: T) => void): Subscription {
        return this.rc.subscribe(_ => {
            if (key == _.key) {
                next(_.data);
            }
        });
    }

    /**
     * 将一些第三方的api逻辑时间点融入notificationCenter管理
     * 第三方api使用cocos提供的EventTarget作为事件发送器，因此不需要额外引入代码
     * 这里只把EventTarget接收到的事件转为NotificationCenter消息发布
     */
    subscribeCustomEventTarget() {
    }
}

export const nc = new NotificationCenter();